package com.da.lon.wang.xlg.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.LoginBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.constants.XLGConstants.MethodName;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.ToastUtils;
import com.da.lon.wang.xlg.util.Utils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.da.lon.wang.xlg.wxapi.WXOauthBean;
import com.da.lon.wang.xlg.wxapi.WXUserInfoBean;
import com.tencent.connect.UserInfo;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends BaseActivity implements OnClickListener {

    private final BroadcastReceiver wxSuccess = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String code = intent.getStringExtra("code");
            String errCode = intent.getStringExtra("errCode");
            if (errCode.equals("0") && !TextUtils.isEmpty(code)) {
                getToke(code);
            } else {
                if (errCode.equals("-2")) {

                } else {
                    Toast.makeText(LoginActivity.this, "登录失败",
                            Toast.LENGTH_LONG).show();
                }

            }

        }
    };
    private EditText usernameEdit;
    private EditText passwordEdit;
    private Tencent mTencent;
    private IWXAPI api;
    private ImageView forgetPassword;

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MyApplication.hideInputWindow(passwordEdit, this);
        MyApplication.hideInputWindow(usernameEdit, this);
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        MyApplication.getInstance().addActivity(this);
        setContentView(R.layout.xlg_login);
        registWxSuccessReceiver();
        initView();
        mTencent = Tencent.createInstance(XLGConstants.APP_ID,
                this.getApplicationContext());
        api = WXAPIFactory.createWXAPI(this, XLGConstants.WX_APP_ID, true);
        api.registerApp(XLGConstants.WX_APP_ID);
    }

    private void initView() {
        ImageButton back = (ImageButton) findViewById(R.id.ouka_login_left);
        back.setOnClickListener(this);
        ((TextView) findViewById(R.id.regist)).setOnClickListener(this);
        ((Button) findViewById(R.id.login)).setOnClickListener(this);
        ((Button) findViewById(R.id.qq_login)).setOnClickListener(this);
        ((Button) findViewById(R.id.wx_login)).setOnClickListener(this);
        usernameEdit = (EditText) findViewById(R.id.username);
        passwordEdit = (EditText) findViewById(R.id.password);
        // usernameEdit.setText(PreferenceUtils.getInstance().getSettingStr(PreferencesConfig.USER_NAME,
        // ""));
        forgetPassword = (ImageView) findViewById(R.id.forget_password);
        forgetPassword.setOnClickListener(this);
    }

    /**
     * 登陆
     */

    private void login() {

        String url = XLGConstants.URL + XLGConstants.URL_HEAD
                + MethodName.LOGIN;
        HttpLoader<LoginBean> httpLoader = new HttpLoader<LoginBean>(this,
                url, LoginBean.class);
        AjaxParams params = new AjaxParams();
        params.put("username", usernameEdit.getText().toString());
        params.put("password",
                XLGDataUtils.encrypt2MD5(passwordEdit.getText().toString()));
        params.put(
                "token",
                XLGDataUtils.encrypt2MD5(XLGConstants.API
                        + XLGConstants.SECRET + MethodName.LOGIN));
        params.put("device_type", "1");
        httpLoader.setManagerListener(new OnWebLoadListener<LoginBean>() {

            @Override
            public void OnStart() {
                showDialog();

            }

            @Override
            public void OnError(String error) {
                dismissDialog();
                Toast.makeText(LoginActivity.this, "登录失败",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(LoginBean t) {
                dismissDialog();
                if (t != null && t.getCode().equals("000000")) {
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.RANKLOGO,
                            t.getResult().getRanklogo());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.RANKNAME,
                            t.getResult().getRankname());

                    setShopIDAndName(t);

                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.POINTS,
                            t.getResult().getPoints());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.USER_NAME,
                            t.getResult().getUserName());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.USER_KEY,
                            t.getResult().getUser_key());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.USER_ID,
                            t.getResult().getId());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.MERCHANT_ID,
                            t.getResult().getMerchant_id());

                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.USER_TYPE,
                            t.getResult().getUser_type());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.HEAD_LOG,
                            t.getResult().getHead_log());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.USER_BALANCE,
                            t.getResult().getBalance());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.USER_SEX,
                            t.getResult().getSex());

                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.IS_VIP,
                            t.getResult().getIs_vip());

                    Toast.makeText(LoginActivity.this, "登录成功",
                            Toast.LENGTH_SHORT).show();

                    // 发送广播注册别名
                    Intent intent = new Intent();
                    intent.setAction(XLGConstants.TAGANDALIAS_RECEIVED_ACTION);
                    LoginActivity.this.sendBroadcast(intent);

                    Utils.updateUserInfo(LoginActivity.this);
                    delstorecart();
                    if (MyApplication.getIs_skulist_enter_capture() == 1) {
                        startActivity(new Intent(LoginActivity.this,
                                HomeActivity.class));
                        MyApplication
                                .setIs_skulist_enter_capture(0);
                        MyApplication.getInstance().getSkulist_activity().finish();
                    }


                    finish();
                    setResult(RESULT_OK);

                } else {
                    if (t != null) {
                        Toast.makeText(LoginActivity.this, t.getMessage(),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(LoginActivity.this, "登录失败",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        httpLoader.loadData(params);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ouka_login_left:
                finish();
                break;
            case R.id.regist:
                Intent registIntent = new Intent(LoginActivity.this,
                        RegistActivity.class);
                startActivity(registIntent);
                break;
            case R.id.login:
                if (TextUtils.isEmpty(usernameEdit.getText().toString())
                        || TextUtils.isEmpty(passwordEdit.getText().toString())) {
                    Toast.makeText(LoginActivity.this,
                            getString(R.string.input_empty), Toast.LENGTH_SHORT)
                            .show();
                } else {
                    login();
                }
                break;
            case R.id.qq_login:
                qqLogin();
                break;
            case R.id.wx_login:
                final SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "xlg_wx_login";
                api.sendReq(req);
                break;
            case R.id.forget_password:
                Intent intent = new Intent(LoginActivity.this,
                        WebViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("flag", 1200);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            default:
                break;
        }

    }

    public void setShopIDAndName(LoginBean t) {

        if (null != t.getResult().getStore_id()) {
            PreferenceUtils.getInstance().SetSettingString(
                    PreferencesConfig.STORE_ID,
                    t.getResult().getStore_id());
        }
        if (null != t.getResult().getStore_name()) {
            PreferenceUtils.getInstance().SetSettingString(
                    PreferencesConfig.STORE_NAME,
                    t.getResult().getStore_name());
        }
    }

    public void qqLogin() {
        if (mTencent != null && !mTencent.isSessionValid()) {
            mTencent.login(this, "all", new IUiListener() {

                @Override
                public void onError(UiError arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onComplete(Object arg0) {
                    getQQUserInfo();

                }

                @Override
                public void onCancel() {
                    // TODO Auto-generated method stub

                }
            });
        } else {
            mTencent.logout(getApplicationContext());
            mTencent.releaseResource();
        }

    }

    private void getQQUserInfo() {
        UserInfo info = new UserInfo(this, mTencent.getQQToken());
        info.getUserInfo(new IUiListener() {

            @Override
            public void onError(UiError arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onComplete(Object arg0) {
                // TODO Auto-generated method stub
                try {
                    qqLoginSubmit(new JSONObject(arg0.toString()));
                } catch (JSONException e) {
                    Toast.makeText(LoginActivity.this, "登录失败",
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancel() {
                // TODO Auto-generated method stub

            }
        });
    }

    private void qqLoginSubmit(JSONObject jsonObject) {

        try {
            String url = XLGConstants.URL + "Login-oauthtxqq";
            HttpLoader<LoginBean> httpLoader = new HttpLoader<LoginBean>(this,
                    url, LoginBean.class);
            AjaxParams params = new AjaxParams();
            params.put("openid", mTencent.getOpenId());
            params.put("qqtoken", mTencent.getAccessToken());
            params.put("nickname", jsonObject.optString("nickname"));
            params.put("urlk30", jsonObject.optString("figureurl"));
            params.put("urlk50", jsonObject.optString("figureurl_1"));
            params.put("urlk100", jsonObject.optString("figureurl_2"));
            params.put("urlq40", jsonObject.optString("figureurl_qq_1"));
            params.put("urlq100", jsonObject.optString("figureurl_qq_2"));
            params.put("gender", jsonObject.optString("gender"));
            params.put("status", "101");
            params.put("device_type", "1");
            params.put(
                    "token",
                    XLGDataUtils.encrypt2MD5("Login" + XLGConstants.SECRET
                            + "oauthtxqq"));
            httpLoader.setManagerListener(new OnWebLoadListener<LoginBean>() {

                @Override
                public void OnStart() {
                    showDialog();

                }

                @Override
                public void OnError(String error) {
                    dismissDialog();
                    Toast.makeText(LoginActivity.this, "登录失败",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess(LoginBean t) {
                    dismissDialog();
                    if (t != null && t.getCode().equals("000000")) {
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.USER_NAME,
                                t.getResult().getUserName());
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.USER_KEY,
                                t.getResult().getUser_key());
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.USER_ID,
                                t.getResult().getId());
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.MERCHANT_ID,
                                t.getResult().getMerchant_id());

                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.USER_TYPE,
                                t.getResult().getUser_type());
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.HEAD_LOG,
                                t.getResult().getHead_log());
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.USER_BALANCE,
                                t.getResult().getBalance());

                        Utils.updateUserInfo(LoginActivity.this);
                        delstorecart();
                        Toast.makeText(LoginActivity.this, "登录成功",
                                Toast.LENGTH_SHORT).show();
                        if (getIntent().getBooleanExtra("isGotoHome", true)) {
                            Intent homeIntent = new Intent(LoginActivity.this,
                                    HomeActivity.class);
                            startActivity(homeIntent);
                        }
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        if (t != null) {
                            Toast.makeText(LoginActivity.this, t.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(LoginActivity.this, "登录失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });

            httpLoader.loadData(params);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    private void wxLoginSubmit(WXUserInfoBean wxUserInfoBean) {

        try {
            String url = XLGConstants.URL + "Login-oauthtxqq";
            HttpLoader<LoginBean> httpLoader = new HttpLoader<LoginBean>(this,
                    url, LoginBean.class);
            AjaxParams params = new AjaxParams();
            params.put("openid", wxUserInfoBean.openid);
            params.put("nickname", wxUserInfoBean.nickname);
            params.put("unionid", wxUserInfoBean.unionid);
            params.put("urlq100", wxUserInfoBean.headimgurl);
            if (wxUserInfoBean.sex.equals("1")) {
                params.put("gender", "男");
            } else if (wxUserInfoBean.sex.equals("2")) {
                params.put("gender", "女");
            } else {
                params.put("gender", "女");
            }
            params.put("status", "1011");
            params.put("device_type", "1");
            params.put(
                    "token",
                    XLGDataUtils.encrypt2MD5("Login" + XLGConstants.SECRET
                            + "oauthtxqq"));
            httpLoader.setManagerListener(new OnWebLoadListener<LoginBean>() {

                @Override
                public void OnStart() {

                }

                @Override
                public void OnError(String error) {
                    dismissDialog();
                    Toast.makeText(LoginActivity.this, "登录失败",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess(LoginBean t) {
                    dismissDialog();
                    if (t != null && t.getCode().equals("000000")) {
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.USER_NAME,
                                t.getResult().getUserName());
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.USER_KEY,
                                t.getResult().getUser_key());
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.USER_ID,
                                t.getResult().getId());
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.MERCHANT_ID,
                                t.getResult().getMerchant_id());

                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.USER_TYPE,
                                t.getResult().getUser_type());
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.HEAD_LOG,
                                t.getResult().getHead_log());
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.USER_BALANCE,
                                t.getResult().getBalance());

                        Utils.updateUserInfo(LoginActivity.this);
                        delstorecart();
                        Toast.makeText(LoginActivity.this, "登录成功",
                                Toast.LENGTH_SHORT).show();
                        if (getIntent().getBooleanExtra("isGotoHome", true)) {
                            Intent homeIntent = new Intent(LoginActivity.this,
                                    HomeActivity.class);
                            startActivity(homeIntent);
                        }
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        if (t != null) {
                            Toast.makeText(LoginActivity.this, t.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(LoginActivity.this, "登录失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });

            httpLoader.loadData(params);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void getToke(String code) {

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + XLGConstants.WX_APP_ID + "&secret="
                + XLGConstants.WX_App_Secret + "&code=" + code
                + "&grant_type=authorization_code";
        HttpLoader<WXOauthBean> httpLoader = new HttpLoader<WXOauthBean>(this,
                url, WXOauthBean.class);
        httpLoader.setManagerListener(new OnWebLoadListener<WXOauthBean>() {

            @Override
            public void OnStart() {
                showDialog();

            }

            @Override
            public void OnError(String error) {
                dismissDialog();
                Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_LONG)
                        .show();

            }

            @Override
            public void onSuccess(WXOauthBean t) {
                if (t != null && !TextUtils.isEmpty(t.access_token)) {
                    getUserInfo(t.access_token, t.openid);
                } else {
                    Toast.makeText(LoginActivity.this, "登录失败",
                            Toast.LENGTH_LONG).show();
                }

            }
        });
        httpLoader.loadData();
    }

    private void getUserInfo(String access_token, String openid) {

        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token + "&openid=" + openid;
        HttpLoader<WXUserInfoBean> httpLoader = new HttpLoader<WXUserInfoBean>(
                this, url, WXUserInfoBean.class);
        httpLoader.setManagerListener(new OnWebLoadListener<WXUserInfoBean>() {

            @Override
            public void OnStart() {
                // TODO Auto-generated method stub

            }

            @Override
            public void OnError(String error) {
                Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_LONG)
                        .show();
                dismissDialog();
            }

            @Override
            public void onSuccess(WXUserInfoBean t) {
                if (t != null) {
                    // Toast.makeText(LoginActivity.this, t.nickname,
                    // Toast.LENGTH_LONG).show();
                    wxLoginSubmit(t);
                } else {
                    Toast.makeText(LoginActivity.this, "登录失败",
                            Toast.LENGTH_LONG).show();
                }
            }
        });
        httpLoader.loadData();
    }

    private void registWxSuccessReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(XLGConstants.WX_SUCCESS);
        registerReceiver(wxSuccess, intentFilter);
    }

    private void unregistWxSuccessReceiver() {
        unregisterReceiver(wxSuccess);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregistWxSuccessReceiver();
    }


    private void delstorecart() {

        String url = XLGConstants.URL + "login-delstorecart";
        HttpLoader<LoginBean> httpLoader = new HttpLoader<LoginBean>(this,
                url, LoginBean.class);
        AjaxParams params = new AjaxParams();
        params.put("id", MyApplication.getUserId());
        params.put("shop_id", MyApplication.getShopId());
        params.put(
                "token",
                XLGDataUtils.encrypt2MD5("login" + XLGConstants.SECRET
                        + "delstorecart"));
        httpLoader.setManagerListener(new OnWebLoadListener<LoginBean>() {

            @Override
            public void OnStart() {
                showDialog();
            }

            @Override
            public void OnError(String error) {
                dismissDialog();
            }

            @Override
            public void onSuccess(LoginBean t) {
                dismissDialog();
                if (t != null && t.getCode().equals("000000")) {
                    ToastUtils.showShort(LoginActivity.this, t.getMessage());
                }
            }
        });

        httpLoader.loadData(params);


    }

}
